
package org.upt.dcda.presentation;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.upt.dcda.BookManagerBeanRemote;
import org.upt.dcda.BookTagManagerBeanRemote;
import org.upt.dcda.TagManagerBeanRemote;
import org.upt.dcda.db.BookEntity;

/**
 * Servlet implementation class BookCreateServlet
 */
@WebServlet("/BookCreateServlet")
public class BookCreateServlet extends HttpServlet
{

	private static final long			serialVersionUID	= 1L;

	@EJB
	private BookManagerBeanRemote		bookManagerBean;

	@EJB
	private BookTagManagerBeanRemote	bookTagManagerBean;

	@EJB
	private TagManagerBeanRemote		tagManagerBean;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BookCreateServlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException
	{
		try
		{
			if (SessionAttributes.isAdmin(request))
			{
				String title = request.getParameter("title");
				String description = request.getParameter("description");
				int price = Integer.valueOf(request.getParameter("price"));
				int quantity = Integer.valueOf(request.getParameter("quantity"));
				int authorId = Integer.valueOf(request.getParameter("authorId"));

				String[] tags = request.getParameterValues("tags");

				BookEntity book = this.bookManagerBean.addBook(title, description, authorId, price, quantity);

				for (int i = 0; i < tags.length; i++)
				{

					this.bookTagManagerBean.addBookTag(book, this.tagManagerBean.getTagById(Integer.valueOf(tags[i])));
				}

				response.sendRedirect(request.getContextPath() + "/index.jsp");
			}
			else
			{
				response.sendRedirect(request.getContextPath() + "/login.jsp");
			}
		}
		catch (Throwable t)
		{
			getServletContext().log("Caught Exception: " + t, t);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.toString());
		}
	}
}
